using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ViewCart : System.Web.UI.Page
{
    private Invoice _selectedInvoice = new Invoice();
    public Invoice SelectedInvoice
    {
        get
        {
            if (_selectedInvoice.InvoiceId == "")
            {
                try
                {
                    _selectedInvoice = (Invoice)Session["Invoice"];
                }
                catch { }
            }
            return _selectedInvoice;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request["EmptyCart"] != null && Request["EmptyCart"].ToString().ToLower() == "true")
            {
                SelectedInvoice.EmptyCart();
                Session["Invoice"] = SelectedInvoice;
            }
            if (Request["Remove"] != null)
            {
                int productToRemove = int.Parse(Request["Remove"].ToString());
                SelectedInvoice.RemoveProduct(productToRemove);
                Session["Invoice"] = SelectedInvoice;
            }
            RefreshDataInRepeater();
        }       
    }

    private void RefreshDataInRepeater()
    {
        this.rptCartItems.DataSource = SelectedInvoice.InvoiceItems;
        this.rptCartItems.DataBind();
        this.rptCartItems.Visible = (SelectedInvoice.InvoiceItems.Count > 0);
        this.lblEmptyCartMessage.Visible = (this.rptCartItems.Visible == false);
    }

    protected void txtQty_TextChanged(object sender, System.EventArgs e)
    {        
        try
        {
            //loop thru each product in cart
            for (int idx = 0; idx <= rptCartItems.Items.Count; idx++)
            {
                try
                {
                    Label lblIID = (Label)rptCartItems.Items[idx].FindControl("lblProductId");
                    TextBox qtyObj = (TextBox)rptCartItems.Items[idx].FindControl("txtQty");

                    int quantity = 0;
                    if (qtyObj.Text.Trim() != "")
                    {
                        quantity = int.Parse(qtyObj.Text.Trim());
                    }
                    int productId = int.Parse(lblIID.Text);
                    SelectedInvoice.UpdateProductQuantity(productId, quantity);
                    Session["Invoice"] = SelectedInvoice;
                    
                }
                catch {  }

            }
            RefreshDataInRepeater();

        }
        catch {  }
    }
}
